package com.example.huichaoliu;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.huichaoliu.adapters.ActivityShareAdapter;
import com.huichaoliu.app.R;
import com.huichaoliu.data.Config;
import com.rederxu.AsyncTask.ImageTask;
import com.rederxu.farmer.BaseActivity;
import com.rederxu.request.HTTPRequest;
import com.rederxu.request.onRequestOverListener;
import com.source.utils.Utils;

public class DetailGoodsActivity extends BaseActivity implements OnClickListener {

	private WebView webView = null;
	private List<JSONObject> listData = new ArrayList<JSONObject>();
	private int selectionColor = 0;
	private int selectionSize = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_goods_detail);
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.left_button:
			finish();
			break;
		case R.id.btn_add:
			showChoseInfo();
			break;
		case R.id.btn_fitting:
			setResult(RESULT_OK);
			finish();
			break;
		case R.id.right_img_button:
			startActivity(CommentActivity.class);
			break;
		}
	}

	@Override
	public void init() {
		((TextView) findViewById(R.id.title_text)).setText("商品详情");
		findViewById(R.id.left_button).setOnClickListener(this);
		findViewById(R.id.btn_add).setOnClickListener(this);
		findViewById(R.id.btn_fitting).setOnClickListener(this);
		findViewById(R.id.left_button).setOnClickListener(this);
		ImageButton btn = (ImageButton)findViewById(R.id.right_img_button);
		btn.setVisibility(View.VISIBLE);
		btn.setImageResource(R.drawable.ic_edit);
		btn.setOnClickListener(this);
		webView = (WebView) findViewById(R.id.webView);
	}

	@Override
	public void initData() {
		webView.loadUrl(getIntent().getStringExtra("url"));
		try{
			JSONObject jo = new JSONObject();
			jo.put("userId", Config.getUserId(this));
			jo.put("commodityId", getIntent().getStringExtra("code"));
			Bundle bundle = new Bundle();
			bundle.putString("request", Utils.requestParamsEncode(jo));
			HTTPRequest.POST(this, Config.REQUEST_URLS.URL_SHOPPING_COMMODITY_INFO, bundle, new onRequestOverListener() {
				@Override
				public void onRequestOver(String result) {
					try{
						JSONObject jo = new JSONObject(result);
						if(jo.getInt("code") != 0){
							showToast(jo.getString("message"));
							return;
						}
						jo = jo.getJSONObject("response");
						listData.clear();
						List<String> listColor = new ArrayList<String>();
						JSONArray ja = jo.getJSONArray("commodityNumber");
						for(int i = 0; i < ja.length();i++){
							jo = ja.getJSONObject(i);
							String color = jo.getString("color");
							if(!listColor.contains(color)){
								listColor.add(color);
								JSONObject joColor = new JSONObject();
								joColor.put("color", color);
								joColor.put("size", new JSONArray());
								listData.add(joColor);
							}
						}
						for(int i = 0; i < ja.length();i++){
							jo = ja.getJSONObject(i);
							int pos = listColor.indexOf(jo.getString("color"));
							JSONObject joColor = listData.get(pos);
							JSONArray jaSize = joColor.getJSONArray("size");
							jaSize.put(jo);
						}
					}catch(JSONException e){
						e.printStackTrace();
					}
				}
			});
		}catch(Exception e){
			
		}
	}

	@Override
	public void onNetworkChanged(boolean isMobNetConnected,
			boolean isWifiConnected) {
		// TODO Auto-generated method stub

	}

	private void showChoseInfo(){
		AlertDialog.Builder builder = new Builder(mContext);
		final AlertDialog mDialog = builder.create();
		Window window = mDialog.getWindow();
		window.setGravity(Gravity.BOTTOM);
		mDialog.show();
		mDialog.setCancelable(true);
		window.setContentView(R.layout.dialog_chose_info);
		final TextView tv_last = (TextView) window.findViewById(R.id.tv_last);
		TextView tv_name = (TextView) window.findViewById(R.id.tv_name);
		tv_name.setText(getIntent().getStringExtra("name"));
		ImageView ic_cover = (ImageView) window.findViewById(R.id.ic_cover);
		ImageTask task = new ImageTask(ic_cover,Config.getFolderImages(),null);
		task.execute(getIntent().getStringExtra("cover"));
		final GridView gridViewColor = (GridView) window.findViewById(R.id.gridViewColor);
		gridViewColor.setAdapter(new ColorAdapter());
		final GridView gridViewSize = (GridView) window.findViewById(R.id.gridViewSize);
		gridViewSize.setAdapter(new SizeAdapter());
		try{
			JSONObject jo = ((SizeAdapter)gridViewSize.getAdapter()).getItem(selectionSize);
			String last = "库存  " + jo.getString("number");
			tv_last.setText(last);
		}catch(JSONException e){
			e.printStackTrace();
		}
		gridViewColor.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long arg3) {
				selectionColor = position;
				selectionSize = 0;
				gridViewColor.setAdapter(new ColorAdapter());
				gridViewSize.setAdapter(new SizeAdapter());
			}
		});
		gridViewSize.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long arg3) {
				selectionSize = position;
				gridViewSize.setAdapter(new SizeAdapter());
				try{
					JSONObject jo = ((SizeAdapter)gridViewSize.getAdapter()).getItem(position);
					String last = "库存  " + jo.getString("number");
					tv_last.setText(last);
				}catch(JSONException e){
					e.printStackTrace();
				}
			}
		});
		window.findViewById(R.id.btn_go).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mDialog.dismiss();
				try{
				JSONObject jo = new JSONObject();
				jo.put("userId", Config.getUserId(mContext));
				jo.put("commodityId", getIntent().getStringExtra("code"));
				jo.put("numberId", ((SizeAdapter)gridViewSize.getAdapter()).getItem(selectionSize).getString("id"));
				Log.e("jo", jo.toString());
				Bundle bundle = new Bundle();
				bundle.putString("request", Utils.requestParamsEncode(jo));
				HTTPRequest.POST(mContext, Config.REQUEST_URLS.URL_SHOPPING_ADD_BAG, bundle, new onRequestOverListener() {
					@Override
					public void onRequestOver(String result) {
						try{
							JSONObject jo = new JSONObject(result);
							showToast(jo.getString("message"));
						}catch(JSONException e){
							e.printStackTrace();
						}
					}
				});
			}catch(Exception e){
				e.printStackTrace();
			}
			}
		});
	}
	
	private class SizeAdapter extends BaseAdapter{
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			try {
				return listData.get(selectionColor).getJSONArray("size").length();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return 0;
			}
		}

		@Override
		public JSONObject getItem(int position) {
			// TODO Auto-generated method stub
			try {
				return listData.get(selectionColor).getJSONArray("size").getJSONObject(position);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView tv_data = null;
			if(convertView == null){
				convertView = new TextView(mContext);
				tv_data = (TextView)convertView;
				tv_data.setTextColor(0xfff0f0f2);
				tv_data.setGravity(Gravity.CENTER);
			}else{
				tv_data = (TextView)convertView;
			}
			try {
				tv_data.setText(listData.get(selectionColor).getJSONArray("size").getJSONObject(position).getString("size"));
			} catch (JSONException e) {
				e.printStackTrace();
				tv_data.setText("error");
			}
			if(position == selectionSize){
				convertView.setBackgroundResource(R.drawable.round_red_info);
			}else{
				convertView.setBackgroundResource(R.drawable.round_grey_info);
			}
			return convertView;
		}
		
	}
	
	private class ColorAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			try {
				return listData.get(position).getString("color");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView tv_data = null;
			if(convertView == null){
				convertView = new TextView(mContext);
				tv_data = (TextView)convertView;
				tv_data.setTextColor(0xfff0f0f2);
				tv_data.setGravity(Gravity.CENTER);
			}else{
				tv_data = (TextView)convertView;
			}
			try {
				tv_data.setText(listData.get(position).getString("color"));
			} catch (JSONException e) {
				e.printStackTrace();
				tv_data.setText("error");
			}
			if(position == selectionColor){
				convertView.setBackgroundResource(R.drawable.round_red_info);
			}else{
				convertView.setBackgroundResource(R.drawable.round_grey_info);
			}
			return convertView;
		}
		
	}
	
//	private class Adapter extends BaseAdapter{
//		
//		@Override
//		public int getCount() {
//			// TODO Auto-generated method stub
//			return jaData.length();
//		}
//
//		@Override
//		public Object getItem(int position) {
//			// TODO Auto-generated method stub
//			try {
//				return jaData.getJSONObject(position).getInt("id");
//			} catch (JSONException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				return null;
//			}
//		}
//
//		@Override
//		public long getItemId(int position) {
//			// TODO Auto-generated method stub
//			return 0;
//		}
//
//		@Override
//		public View getView(int position, View convertView, ViewGroup parent) {
//			TextView tv_data = null;
//			if(convertView == null){
//				convertView = new TextView(mContext);
//				tv_data = (TextView)convertView;
//				tv_data.setTextColor(0xfff0f0f2);
//				tv_data.setGravity(Gravity.CENTER);
//			}else{
//				tv_data = (TextView)convertView;
//			}
//			try {
//				tv_data.setText(jaData.getJSONObject(position).getString("color") + "  " + jaData.getJSONObject(position).getString("size"));
////				Log.e("name", jaData.getJSONObject(position).getString("name"));
//			} catch (JSONException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				tv_data.setText("error");
//			}
//			if(position == selection){
//				convertView.setBackgroundResource(R.drawable.round_red_info);
//			}else{
//				convertView.setBackgroundResource(R.drawable.round_grey_info);
//			}
//			return convertView;
//		}
//		
//	}
}
